package com.itheima52.mobilesafe.activity;

import com.itheima52.mobilesafe.R;
import com.itheima52.mobilesafe.db.dao.AddressDao;

import android.app.Activity;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Interpolator;
import android.widget.EditText;
import android.widget.TextView;

/**
 * 归属地查询页面
 * 
 * @author ludaxu
 * 
 */
public class AddressActivity extends Activity {
	private EditText etNumber;
	private TextView tvResult;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_address);
		etNumber = (EditText) findViewById(R.id.et_number);
		tvResult = (TextView) findViewById(R.id.tv_result);
		// 监听EditText文本的变化.有变化就调用
		etNumber.addTextChangedListener(new TextWatcher() {

			// 文字发生变化时的回调
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				String address = AddressDao.getAddress(s.toString());
				tvResult.setText(address);
			}

			// 文字发生变化前的回调
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			// 文字发生变化结束后的回调
			@Override
			public void afterTextChanged(Editable s) {

			}
		});

	}

	/**
	 * 开启查询
	 * 
	 * @param view
	 */
	public void query(View view) {
		String number = etNumber.getText().toString().trim();
		if (!TextUtils.isEmpty(number)) {
			String address = AddressDao.getAddress(number);
			tvResult.setText(address);
		} else {
			Animation shake = AnimationUtils.loadAnimation(
					AddressActivity.this, R.anim.shake);
			//
			// shake.setInterpolator(new Interpolator() {
			//
			// @Override
			// public float getInterpolation(float x) {
			// // x相当与持续的时间,y相当移动的距离,两者可以是方程式
			//
			// float y = 0;
			//
			// return y;getFilesDir
			// }
			// });

			etNumber.startAnimation(shake);
			vibrate();
		}

	}

	/**
	 * 手机震动,需要震动的权限.
	 */
	private void vibrate() {
		Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
		// vibrator.vibrate(2000);// 震动2秒钟
		// 先等待1秒,震动2秒,等待1秒,震动3秒,-1表示只执行一次,不循环,如果为0,则从头开始循环.
		// 如果为1,则从第一个参数开始循环.如果为2,则从第二个参数开始循环...不能超过4,运行会有问题
		vibrator.vibrate(new long[] { 1000, 2000, 1000, 3000 }, -1);
		// vibrator.cancel();// 取消震动
	}

}
